/**
 * 
 */
package com.bitBusy.manageyourriches.utilityClasses.filehandlers;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.util.Log;
import au.com.bytecode.opencsv.CSVWriter;

import com.bitBusy.manageyourriches.database.managers.DatabaseOpenRequestors;
import com.bitBusy.manageyourriches.database.managers.DatabaseOpeners;
import com.bitBusy.manageyourriches.database.managers.DateTimeManager;
import com.bitBusy.manageyourriches.database.tables.BasicDetails;

/**
 * @author SumaHarsha
 *
 */
public class ReportFileBuilder extends AsyncTask<Cursor, Void, Boolean> implements DataExtractors, DatabaseOpenRequestors{

	private static final String FILENAME = new StringBuilder("ExpenseReport_").append(DateTimeManager.getCurrentMonth()).append
			(DateTimeManager.getCurrentYear()).append(".csv").toString();
	private File myFile;	
	
	private List<DataExportRequestors> myRequestors;
	
	private HashMap<DatabaseOpeners, Boolean> myDatabaseOpeners;

	
    private Context myContext;
			
			
	/**
	 * @param exportDataActivity
	 */
	public ReportFileBuilder(Context the_context) {
		myContext = the_context;
	//	myProgressDialog = new ProgressDialog(the_context);

		
	}


	@Override
    protected void onPreExecute()

    {
		/*System.out.println("Pre exec");
		myProgressDialog.setMessage(EXPORTING);
		myProgressDialog.show();*/
	}
    
       

    // automatically done on worker thread (separate from UI thread)

			
    protected Boolean doInBackground(final Cursor... args)

    {
    	 
    	  Cursor cursor = args[0];
    	  if (cursor != null)
    	  {
	    	  File exportDir = new File(myContext.getFilesDir(), "");
	          veifyExportDir(exportDir);
	          myFile = new File(exportDir, FILENAME);
	          try
	          {
	        	myFile.createNewFile();
	        	writeIntoFile(myFile, cursor);
	            return true;
	        }
	
	        catch(SQLException sqlEx)
	
	        {
	
	            Log.e(getClass().getCanonicalName(), sqlEx.getMessage(), sqlEx);
	
	            return false;
	
	        }

	        catch (IOException e)
	
	        {
	
	            Log.e(getClass().getCanonicalName(), e.getMessage(), e);
	
	            return false;
	
	        }
    	  }
    	  return false;

    }

    // can use UI thread here

    /**
	 * @param file
	 * @param cursor
	 */
	private void writeIntoFile(File the_file, Cursor the_cursor) {
		  CSVWriter csvWrite;
		try {
			csvWrite = new CSVWriter(new FileWriter(the_file));
		   csvWrite.writeNext(the_cursor.getColumnNames());
		  int noColumns = the_cursor.getColumnCount();
		  String dataColumns[] = new String[noColumns];
          while(the_cursor.moveToNext())
         {
        	  for (int i = 0; i < noColumns; i++)
        	  {
        		  if(the_cursor.getColumnName(i).equals(BasicDetails.DATECOL))
        		  {
        			  dataColumns[i] = DateTimeManager.parseForUserDate(the_cursor.getInt(i));
        		  }
        		  else
        		  {
        			  dataColumns[i] = the_cursor.getString(i);
        		  }

        	  }
                 csvWrite.writeNext(dataColumns);
         }
          csvWrite.close();
          the_cursor.close();
         } catch (IOException e) {
			Log.e(getClass().getCanonicalName(), e.toString());
		}
	}


	/**
	 * @param exportDir
	 */
	private void veifyExportDir(File the_exportDir) {
		if (!the_exportDir.exists())

        {

			the_exportDir.mkdirs();

        }		
	}


	@Override

    protected void onPostExecute(final Boolean the_success)

    {
		/*if(myProgressDialog.isShowing())
		{
			myProgressDialog.dismiss();
		}*/
		closeDB();

		if (the_success)
		{
			notifyRequestors();
		}
		
    }

	/**
	 * 
	 */
	private void notifyRequestors() {
		for(DataExportRequestors requestor: myRequestors)
		{
			if(requestor != null)
			{
				requestor.acceptFile(myFile);
			}
		}		
	}


	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.utilityClasses.filehandlers.DataExtractors#registerRequestors(com.bitBusy.manageyourriches.utilityClasses.filehandlers.DataExportRequestors)
	 */
	@Override
	public void registerRequestors(DataExportRequestors the_requestor) {
		if (myRequestors == null)
		{
			myRequestors = new ArrayList<DataExportRequestors>();
		}
		myRequestors.add(the_requestor);
	}


	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.database.managers.DatabaseOpenRequestors#registerOpener(com.bitBusy.manageyourriches.database.managers.DatabaseOpeners)
	 */
	@Override
	public void registerOpener(DatabaseOpeners the_opener, boolean 	the_iOpened) {
		if(myDatabaseOpeners == null)
		{
			myDatabaseOpeners = new HashMap<DatabaseOpeners, Boolean>();		
		}
		myDatabaseOpeners.put(the_opener, the_iOpened);
	}


	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.database.managers.DatabaseOpenRequestors#closeDB()
	 */
	@Override
	public void closeDB() {
			if (myDatabaseOpeners != null)
			{
				Set<DatabaseOpeners> openers = myDatabaseOpeners.keySet();
				for(DatabaseOpeners opener:openers)
				{
					if (opener != null)
					{
						opener.closeDB(myDatabaseOpeners.get(opener));
					}
				}
				
			}
	}


	
}